package wili.attrMapping.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import wili.attrMapping._user.b1.AttConst;
import wili.attrMapping._user.b1.B1com;
import wili.attrMapping.file.JsonFile;
import wili.c.Ca;
import wili.c.Str9a;
import wili.json.JsonLeaf;

/**
 * 
 * @author weila 2022年10月22日
 */
public class Att9 {
	public static final String AppDir = "D:/bearJ/awilly/attMappingRule";
	public static boolean DEBUG = "asdf".isEmpty();
	public static final String FORMULA = "formula";

	/**
	 * 需用户实现的部分:<br>
	 * 定义新旧属性集、查找旧属性、查找新属性、新属性=fun(规则，旧属性)、规则=fun(旧属性，新属性)
	 * 
	 * @return
	 */
	public static final boolean usage(String msg) {//用户使用
		return true;
	}

	public static boolean ref(String smg) {
		return true;
	}

	static String transformFm(ValueMapingNode rule, AttsObj oldAtts) {
		String toTargetValue = rule.value;
		{// 规则映射值
			if (toTargetValue.contains(AttConst.placeholderOf(FORMULA))) {// 规则有此misc value.
				// Ca.log(updateTimes + ", " + newAtt.key() + ", update: " + toTargetValue);
				Att oldAtt = oldAtts.att(FORMULA);// get misc value from oldObj
				if (oldAtt != null) {
					String fm = oldAtt.value;
					fm = B1com.formularTransform(oldAtts, fm, false);
					toTargetValue = toTargetValue.replace(AttConst.placeholderOf(FORMULA), fm);
				} else {
					Ca.asert(false, "May be rule should not has misc node here" + rule.id);
					// Ca.log("warn:" + "for rule:" + ruleLeaf.id + ", fromObj not has misc value:"
					// + guid);
				}
			}
		}
		toTargetValue = Str9a.removeRedundantBracket('(', ')', toTargetValue);
		return B1com.closeFormula(toTargetValue);
	}

	public static Map<String, JsonFile> get_id2fileMap(List<AttsFile> files) {
		if (files == null)
			return null;
		Map<String, JsonFile> ret = new HashMap<>();
		for (AttsFile ele : files) {
			JsonFile file = (JsonFile) ele;
			List<JsonLeaf> lis = file.root.findLeafs("guid", null, -1);
			for (JsonLeaf id : lis)
				ret.put(id.stringValue, file);
		}
		return ret;
	}

	public static final List<String> msgs = new ArrayList<>();
	public static int updateTimes;

	public static String log7(Object... mm) {
		String ret = AttConst.Bugs.msg(mm);
		if ("".isEmpty() || UserConf.ShowRuleID) {
			Ca.log(ret);
		}
		Att9.msgs.add(ret);
		return ret;
	}

	public static void debug(Object... mm) {
		if (!Att9.DEBUG)
			return;
		Ca.log(1, mm);
	}

	public static void printMsgs() {
		if (msgs.isEmpty()) {
			Ca.log("\n>>> Target file already updated.");
			return;
		}
		for (int i = 0; i < msgs.size(); i++) {
			String msg = msgs.get(i);
			Ca.log(msg);
		}
	}

	public static int inc;
}
